<template>
    <div>
        <van-field
          v-model="telCode"
          clearable
          placeholder="请输入短信验证码"
        >
          <template #button>
            <van-button @click="sendCode" :disabled="codeFlag" size="small" type="default">{{text}}</van-button>
          </template>
        </van-field>
        <van-button class="login_button" :disabled="!flag" round type="danger" size="large" @click="docheckcode">下一步</van-button>
    </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Field, Button, Toast } from 'vant'
import { dosendmsgcode, docheckcode } from '@/api/register'

Vue.use(NavBar)
Vue.use(Field)
Vue.use(Button)
Vue.use(Toast)
export default {
  computed: {
    flag () {
      return /\d{5}/.test(this.telCode)
    }
  },
  data () {
    return {
      tel: '',
      telCode: '',
      time: 10,
      text: '发送验证码',
      timer: null,
      codeFlag: false
    }
  },
  mounted () {
    this.sendCode()
  },
  methods: {
    async sendCode () {
      var res = await dosendmsgcode({
        tel: localStorage.getItem('tel')
      })
      console.log(res)
      this.timer = setInterval(() => {
        this.time--
        if (this.time <= 0) {
          this.text = '发送验证码'
          this.codeFlag = false
          this.time = 10
          clearInterval(this.timer)
        } else {
          this.text = this.time + 's重新发送'
          this.codeFlag = true
        }
      }, 1000)
    },
    async docheckcode () {
      var res = await docheckcode({
        tel: localStorage.getItem('tel'),
        telcode: this.telCode
      })
      console.log(res)
      if (res.data.code === '10007') {
        Toast('验证码错误')
      } else {
        this.$router.push({ path: '/register/step3' })
      }
    }
  }
}
</script>

<style lang="stylus">
</style>
